package com.radar.task.qh;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.google.gson.Gson;
import com.radar.algorithm.MathCommon;
import com.radar.common.DateConstants;
import com.radar.common.ProductType;
import com.radar.io.RadarGridData;
import com.radar.io.radar346.Product346;
import com.radar.license.LicenseVerify;
import com.radar.task.cd.Constants;
import com.radar.visualize.PolarMap;
import com.radar.visualize.RasterMap;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.filefilter.RegexFileFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
@Service(value = "Product346Task")
public class Product346Task {

    @Autowired
    private LicenseVerify licenseVerify;

//    @Scheduled(cron = "0 0/2 * * * ? ")
    @Scheduled(fixedDelay = 30 * 1000)
    public void read346Product() {
        if (Constants.jz_001) {
            return;
        }
//        if (!licenseVerify.verify()) {
//            licenseVerify.installLicense();
//            return;
//        }

        long time = System.currentTimeMillis();
        String[] prds = Constants.rootPath.split(";");
        List<File> files = new ArrayList<>();
        for (String prdinfo : prds) {
            if (FileUtil.isDirectory(prdinfo)) {
                files.addAll(FileUtil.loopFiles(prdinfo, new RegexFileFilter("^P(\\d{14}).(.*?)$")).stream()
                        .filter(i -> i.getName().length() == 19)
                        .sorted(Comparator.comparingLong(i -> Long.parseLong(i.getName().substring(1, 1 + 14))))
                        .collect(Collectors.toList()));

//                files.addAll(FileUtil.loopFiles(prdinfo, new RegexFileFilter("^LD(\\d{14})(\\d{3}).PT346$")).stream()
//                        .sorted(Comparator.comparingLong(i -> Long.parseLong(i.getName().substring(2, 2 + 14))))
//                        .collect(Collectors.toList()));
            }
        }
        for (File file : files) {
            String next = file.getName();
            if (FileUtil.exist(file.getAbsolutePath() + ".OK")) {
                continue;
            } else {
                FileUtil.touch(file.getAbsolutePath() + ".OK");
            }
            try {
                log.info("start parse pre radar 362 product file : {} ", next);
                parse346(file);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("parse radar error file : {}", next);
            }
        }
        log.info("sum time : {}", System.currentTimeMillis() - time);
    }

    public void parse346(File file) throws Exception {
        String output = Constants.ncPath + File.separator + "346" + File.separator;
        String date = file.getName().substring(1, 15);
//        String type = file.getName().substring(file.getName().length() - 3, file.getName().length());

        String type = file.getName().split("\\.")[1];
        Product346 product346 = new Product346();
        PolarMap polarMap = new PolarMap(null);
        RasterMap rasterMap = new RasterMap(null);
        BufferedImage bufferedImage = null;
//        if (file.getName().contains("PT346")) {
//            CinradRadar cinradRadar = new CinradRadar();
//            date = file.getName().substring(2, 16);
//            FileUtil.mkdir(output + date + File.separator);
//            cinradRadar.setNetcdfFile(output + date + File.separator + file.getName() + ".nc");
//            cinradRadar.parse(file.getAbsolutePath(), CinradType.RADAR_382);
//            polarMap = new PolarMap(cinradRadar.radar);
//            bufferedImage = polarMap.simplePolar(PolarMap.buildPolarInfo(0, ProductType.REF).backColor(new Color(0,0,0,0)));
//
//            Map map = new HashMap<>();
//            map.put("globalAttr",cinradRadar.radar.globalAttr);
////            map.put("lon",cinradRadar.radar.);
////            map.put("lat",product346.lat);
////            map.put("Bins",product346.Bins);
////            map.put("MaxL",product346.MaxL);
////            map.put("dateTime", DateUtil.format(product346.dateTime, DateConstants.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
////            map.put("Records", product346.Records);
////            map.put("header", product346.header);
//            FileUtil.writeUtf8String(new Gson().toJson(map),  new File(output + date + File.separator + file.getName() + ".setting"));
//            ImageIO.write(bufferedImage, "png", new File(output + date + File.separator + file.getName() + ".png"));
//            ImageIO.write(polarMap.simplePolar(PolarMap.buildPolarInfo(0, ProductType.VEL).backColor(new Color(0,0,0,0))), "png", new File(output + date + File.separator + file.getName() + "_VEL.png"));
//            ImageIO.write(polarMap.simplePolar(PolarMap.buildPolarInfo(0, ProductType.SW).backColor(new Color(0,0,0,0))), "png", new File(output + date + File.separator + file.getName() + "_SW.png"));
//
//            cinradRadar.radar.flush();
//            cinradRadar.radar.close();
//            return;
//        }
        RadarGridData project = null;
        if (type.contains("ET") || type.contains("EB")) {
            product346.parse(file.getAbsolutePath(), ProductType.ET);
            project = product346.project(ProductType.REF);
            bufferedImage = rasterMap.drawSingleRaster(MathCommon.decode(project.radarData, ProductType.REF),
                    ProductType.ET, new Color(0, 0, 0, 0));
        }
//        if (type.contains("VP") || type.contains("VC")) {
//            product346.parse(file.getAbsolutePath(), ProductType.VEL);
//            project = product346.project(ProductType.REF);
//            bufferedImage = rasterMap.drawSingleRaster(MathCommon.decode(project.radarData, ProductType.REF),
//                    ProductType.ET, new Color(0, 0, 0, 0));
//        }
        if (type.contains("VIL")) {
            product346.parse(file.getAbsolutePath(), ProductType.VIL);
            project = product346.project(ProductType.REF);
            bufferedImage = rasterMap.drawSingleRaster(MathCommon.decode(project.radarData, ProductType.REF),
                    ProductType.VIL, new Color(0, 0, 0, 0));

//            bufferedImage =
//                    polarMap.simplePolarProduct(
//                            PolarMap.buildPolarInfo(0, ProductType.VIL)
//                                    .backColor(new Color(0, 0, 0, 0))
//                            , product346.data, product346.azi);
        }
        if (type.contains("ZP") || type.contains("CR") || type.contains("UP") || type.contains("ZC")) {
            product346.parse(file.getAbsolutePath(), ProductType.REF);
            project = product346.projectNoZip();
            bufferedImage = rasterMap.drawSingleRaster(project.data, ProductType.CR, new Color(0, 0, 0, 0));

//            bufferedImage =
//                    polarMap.simplePolarProduct(
//                            PolarMap.buildPolarInfo(0, ProductType.REF)
//                                    .backColor(new Color(0, 0, 0, 0))
//                            , product346.data, product346.azi);
        }
        if (bufferedImage != null) {
            FileUtil.mkdir(output + date + File.separator);
            Map map = new HashMap<>();
            map.put("BinLength", product346.BinLength);
            map.put("lon", product346.lon);
            map.put("lat", product346.lat);
            map.put("extent", project.getExtent());
            map.put("Bins", product346.Bins);
            map.put("MaxL", product346.MaxL);
            map.put("dateTime", DateUtil.format(product346.dateTime, DateConstants.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
            map.put("Records", product346.Records);
            FileUtil.writeUtf8String(new Gson().toJson(map), new File(output + date + File.separator + file.getName() + ".setting"));

            ImageIO.write(bufferedImage, "png", new File(output + date + File.separator + file.getName() + ".png"));
        }
    }

    public static void main(String[] args) throws Exception {
//        CinradRadar cinradRadar = new CinradRadar();
//        cinradRadar.parse("Z:\\LD20220424200947744.VT382\\LD20130906150301453.VT346", CinradType.RADAR_382);
//        PolarMap polarMap = new PolarMap(cinradRadar.radar);
//        for (int i = 0; i < cinradRadar.radar.getElevation().length; i++) {
//            BufferedImage bufferedImage = new RasterMap(cinradRadar.radar).simplePPI(RasterMap.buildRasterInfo(ProductType.REF), i);
////            BufferedImage bufferedImage = polarMap.simplePolar(PolarMap.
////                    buildPolarInfo(i, ProductType.REF)
////                    .simpleDetail(true));
//            ImageIO.write(bufferedImage, "png", new File("D:\\test" + i + ".png"));
//        }
//        BufferedImage crimg = new RasterMap(cinradRadar.radar).simpleCR(RasterMap.buildRasterInfo(ProductType.CR));
//        ImageIO.write(crimg, "png", new File("D:\\cr.png"));
//        cinradRadar.radar.flush();
        Product346 product346 = new Product346();
        product346.parse("E:\\data\\radar\\input\\P20220904181337.CR0", ProductType.REF);
        RadarGridData project = product346.project(ProductType.REF);
        System.out.println();
//        bufferedImage = rasterMap.drawSingleRaster(MathCommon.decode(project.radarData,
//                ProductType.REF), ProductType.CR, new Color(0, 0, 0, 0));

    }

}
